const div = document.createElement('div')
const downloadLatestBtn = document.createElement('span')
const downloadAllBtn = document.createElement('span')

div.style.position = 'fixed'
div.style.top = '20px'
div.style.right = '50px'
div.style.color = 'white'
div.style.zIndex = '1000'

downloadLatestBtn.textContent = '下载最新'
downloadLatestBtn.style.textDecoration = 'underline'
downloadLatestBtn.style.cursor = 'pointer'
downloadLatestBtn.style.marginRight = '10px'

downloadAllBtn.textContent = '下载全部'
downloadAllBtn.style.textDecoration = 'underline'
downloadAllBtn.style.cursor = 'pointer'

div.appendChild(downloadLatestBtn)
div.appendChild(downloadAllBtn)

chrome.storage.local.get({ showDownloadButton: true }, (items) => {
  if (items.showDownloadButton) {
    document.body.appendChild(div)
  }
})

async function download() {
  const copyBtns = document.querySelectorAll('.ds-flex .ds-flex .ds-icon-button:first-child')
  if (copyBtns.length == 0) {
    return
  }

  let content = ''
  if (this == downloadLatestBtn) {
    copyBtns[copyBtns.length - 1].click()
    content = await navigator.clipboard.readText()
  } else {
    for (let i = 0; i < copyBtns.length; i++) {
      copyBtns[i].click()
      content += await navigator.clipboard.readText()
      if (i != copyBtns.length - 1) {
        content += "\n\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n\n"
      }
    }
  }

  const objectUrl = URL.createObjectURL(new Blob([content]))
  chrome.storage.local.get({ filenamePrefix: 'deepseek-chat-' }, async (items) => {
    const response = await chrome.runtime.sendMessage({ objectUrl: objectUrl, filenamePrefix: items.filenamePrefix })
    URL.revokeObjectURL(objectUrl)
  })

}

downloadLatestBtn.onclick = download
downloadAllBtn.onclick = download